﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Schema;
using ecdl.demo.persistence;
using Ninject;

namespace ecdl.demo.model.question {
  
    public class Questionaire : ITaskProvider{

        private static readonly string DEFAULT_XML = "ecdl.demo.model.questionaire.Questionaire.xml";
        private static readonly string DEFAULT_XSD = "ecdl.demo.model.questionaire.Questionaire.xsd";


        //Display the validation error.
        private static void ValidationEventHandle(object sender, ValidationEventArgs args) {
            Console.WriteLine("\r\n\tValidation error: " + args.Message);
        }

        private static XmlSchema GetDefaultXSDFile() {
            System.IO.Stream schemaStream = typeof(Questionaire).Assembly.GetManifestResourceStream(DEFAULT_XSD);
            return XmlSchema.Read(schemaStream, ValidationEventHandle);
        }

        private static XmlReader OpenDefaultFile() {
            XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.ValidationType = ValidationType.Schema;
            readerSettings.Schemas.Add(GetDefaultXSDFile());
            readerSettings.DtdProcessing = DtdProcessing.Ignore;

            readerSettings.ValidationEventHandler += ValidationEventHandle;
            System.IO.Stream stream = typeof(Questionaire).Assembly.GetManifestResourceStream(DEFAULT_XML);
            XmlReader xmlReader = XmlReader.Create(stream, readerSettings);

            return xmlReader;
        }

        public static Questionaire GetDefaultQuestionaire() {
            XmlSerializer serializer = new XmlSerializer(typeof(Questionaire));
            Questionaire questionaire = (Questionaire)serializer.Deserialize(OpenDefaultFile());
            return questionaire;
        }

        public Questionaire() {
            Questions = new List<QuestionDTO>();
        }

        [XmlElement("Question")]
        public List<QuestionDTO> Questions { get; set; }



        public IEnumerable<ITask> GetTasks(ModelFactory modelFactory) {
            List<ITask> tasks = new List<ITask>();
            foreach (var item in Questions) {
                tasks.Add(item.ToModel(modelFactory));
            }
            return tasks;
        }
    }
}
